import 'package:sqflite/sqflite.dart';
import 'package:sqflite/sqlite_api.dart';

import 'sqflite_helper.dart';

final String _id = 'id';
final String _name = 'name';
final String _age = 'age';

class Person {
  int id;
  String name;
  int age;

  Person(this.id, this.name, this.age);

  Map<String, dynamic> toMap() {
    Map<String, dynamic> map = {
      _name: name,
      _age: age,
    };
    return map;
  }

  Person.fromMap(Map<String, dynamic> map) {
    id = map[_id];
    name = map[_name];
    age = map[_age];
  }
}

class PersonProvider {
  static PersonProvider _instance;

  factory PersonProvider() => _getInstance();

  static PersonProvider _getInstance() {
    if (_instance == null) {
      _instance = PersonProvider._();
    }
    return _instance;
  }

  //私有构造
  PersonProvider._();

  static const String _table = 'ta_person';
  String createSql =
      'CREATE TABLE $_table ($_id INTEGER PRIMARY KEY, $_name TEXT, $_age INTEGER)';

  Future insert(Person person) async {
    var _database = await SqfliteHelper().db;
    return await _database.insert(_table, person.toMap());
  }

  Future inserts(List<Person> persons) async {
    var _database = await SqfliteHelper().db;
    Batch batch = _database.batch();
    persons.forEach((element) {
      batch.insert(_table, element.toMap());
      print('${DateTime.now()}--${element.toMap()}');
    });
    return await batch.commit();
  }

  Future<Person> query(int id) async {
    var _database = await SqfliteHelper().db;
    List<Map> maps = await _database.query(
      _table,
      columns: [_id, _name, _age],
      where: '$_id=?',
      whereArgs: [id],
      limit: 1,
    );
    if (maps.length == 1) {
      return Person.fromMap(maps.first);
    } else {
      return null;
    }
  }

  Future<List<Person>> queryAll() async {
    var _database = await SqfliteHelper().db;
    List<Map> maps = await _database.query(_table);
    List<Person> persons = [];
    maps.forEach((element) {
      persons.add(Person.fromMap(element));
    });
    return persons;
  }

  Future delete(int id) async {
    var _database = await SqfliteHelper().db;
    return await _database.delete(
      _table,
      where: '$_id=?',
      whereArgs: [id],
    );
  }

  Future update(Person person) async {
    var _database = await SqfliteHelper().db;
    return await _database.update(
      _table,
      person.toMap(),
    );
  }

  Future close() async {
    var _database = await SqfliteHelper().db;
    return await _database.close();
  }

  Future drop() async {
    String path = await getDatabasesPath();
    path = '$path/demo.db';
    return await deleteDatabase(path);
  }

  Future clear() async {
    var _database = await SqfliteHelper().db;
    await _database.delete(_table);
  }
}
